﻿@{
    ViewData["Title"] = "我的应用";
}
@section style{
    <link href="~/css/appx.css" rel="stylesheet" type="text/css" />
    <link href="~/libs/a-image/a-image.css" rel="stylesheet" type="text/css" />
}
@section script{
    <script src="~/js/ajaxfileupload.js"></script>
    <script src="~/js/apage.js"></script>
    <script src="~/libs/a-image/a-image.js"></script>
    <script>
        $.image()
        var vm = new Vue({
            el: '#app',
            data: {
                usercode: '@ViewBag.UserCode',
                apps: [],
                selectedApp: {},
                tables: [],
                selectedTable: {},
                tabIndex: 'data',
                dataList: [],
                struc: [],
                pageIndex: 1,
                pageSize: 15,

                isShowDetail: false,
                showDetailData: [],

                showApp: false,
                editApp: {},

                showTable: false,
                editTable: {},
                filedFileName: '',

                fileIdName: '',
                showData: false,
                editData: {},
                editIndex: -1
            },
            methods: {
                axGetApps() {
                    let idx = alay.loading()
                    $.post('/App/AxGetApps', null, res => {
                        alay.close(idx)
                        this.apps = res.data
                    })
                },
                axGetTables() {
                    let idx = alay.loading()
                    $.post('/App/AxGetTabs', { appid: this.selectedApp.id }, res => {
                        alay.close(idx)
                        this.tables = res.data
                    })
                },
                axGetData() {
                    let params = {
                        tableid: this.selectedTable.id,
                        page: this.pageIndex,
                        size: this.pageSize
                    }
                    let idx = alay.loading()
                    $.post('/App/AxGetDataPage', params, res => {
                        alay.close(idx)
                        this.dataList = res.data.data
                        this.struc = res.data.structure
                        apage.render({
                            elm: '#mypage',
                            count: res.data.count,
                            index: this.pageIndex,
                            size: this.pageSize,
                            click: o => {
                                this.pageIndex = o.page
                                this.axGetData()
                            }
                        })
                    })
                },
                selectApp(appid) {
                    if (this.selectedApp.id == appid) return
                    apage.remove()
                    this.tables = []
                    this.selectedTable = []
                    this.dataList = []
                    this.struc = []
                    this.pageIndex = 1
                    this.pageSize = 15
                    this.selectedApp = this.apps.find(x => {
                        return x.id == appid
                    })
                    this.axGetTables()
                },
                selectTable(tableid) {
                    if (this.selectedTable.id == tableid) return
                    this.pageIndex = 1
                    this.pageSize = 15
                    this.dataList = []
                    this.struc = []
                    this.selectedTable = this.tables.find(x => {
                        return x.id == tableid
                    })
                    this.axGetData()
                },
                selectTab(val) {
                    this.tabIndex = val
                },
                shortContent(val, len) {
                    if (!val) return ''
                    if (!len) len = 128
                    if (val.length < len) return val
                    return val.substr(0, len) + '...'
                },
                addFiled() {
                    this.struc.push({
                        name: '',
                        type: 'string',
                        defaultvalue: ' ',
                        des: '',
                        isnew: true
                    })
                },
                showAppForm(id) {
                    this.showApp = true
                    if (id === 0) {
                        this.editApp = {
                            id: 0,
                            name: '',
                            note: '',
                            appid: ''
                        }
                    } else {
                        let app = {}, temp = this.apps.find(x => {
                            return x.id == id
                        })
                        for (im in temp) app[im] = temp[im]
                        this.editApp = app
                    }
                },
                saveApp() {
                    let idx = alay.loading()
                    $.post('/App/AxEditApp', this.editApp, res => {
                        alay.close(idx)
                        if (res.state) {
                            this.showApp = false
                            this.axGetApps()
                        }
                        alay.msg(res.msg)
                    })
                },
                showTableForm(id) {
                    if (!this.selectedApp.id) {
                        alay.msg('请选择应用')
                        return
                    }
                    this.showTable = true
                    if (id === 0) {
                        this.editTable = {
                            id: 0,
                            name: '',
                            note: '',
                            code: ''
                        }
                    } else {
                        let tb = {}, temp = this.tables.find(x => {
                            return x.id == id
                        })
                        for (im in temp) tb[im] = temp[im]
                        this.editTable = tb
                    }
                },
                saveTable() {
                    let idx = alay.loading()
                    this.editTable.appid = this.selectedApp.id
                    $.post('/App/AxEditTable', this.editTable, res => {
                        alay.close(idx)
                        if (res.state) {
                            this.showTable = false
                            this.axGetTables()
                        }
                        alay.msg(res.msg)
                    })
                },
                delApp(id) {
                    alay.confirm('确定删除应用吗？', res => {
                        if (res) {
                            let idx = alay.loading()
                            $.post('/App/AxDelApp', { appid: id }, res => {
                                alay.close(idx)
                                if (res.state) {
                                    this.axGetApps()
                                }
                                alay.msg(res.msg)
                            })
                        }
                    })
                },
                delTable(id) {
                    alay.confirm('确定删除数据表吗？<br><span style="color:red;">将会删除数据表对应的文件！<span>', res => {
                        if (res) {
                            let idx = alay.loading()
                            $.post('/App/AxDelTable', { tableid: id }, res => {
                                alay.close(idx)
                                if (res.state) {
                                    this.axGetTables()
                                }
                                alay.msg(res.msg)
                            })
                        }
                    })
                },
                saveStruc() {
                    if (this.struc.length == 0) {
                        alay.msg('至少拥有一个字段')
                        return
                    }
                    if (!this.selectedTable) {
                        alay.msg('请选择一个数据表')
                        return
                    }
                    let idx = alay.loading()
                    $.post('/App/AxSaveTabStruc', { tableid: this.selectedTable.id, list: this.struc }, res => {
                        alay.close(idx)
                        if (res.state) {
                            this.axGetData()
                        }
                        alay.msg(res.msg)
                    })
                },
                removeFiled(idx) {
                    alay.confirm('确定要删除此字段吗？', res => {
                        if (res) {
                            this.struc.splice(idx, 1)
                        }
                    })
                },
                addData() {
                    if (this.struc.length == 0) {
                        alay.msg('至少拥有一个字段')
                        return
                    }
                    if (!this.selectedTable) {
                        alay.msg('请选择一个数据表')
                        return
                    }
                    let idx = alay.loading()
                    $.post('/App/AxAddData', { tableid: this.selectedTable.id, list: this.struc }, res => {
                        alay.close(idx)
                        if (res.state) {
                            this.axGetData()
                        }
                        alay.msg(res.msg)
                    })
                },
                selectFile(name) {
                    let id = '#upload_' + this.filedFileName + '_' + name
                    $(id).click()
                },
                uploadFile(e, name) {
                    let idx = e.target.dataset.idx
                    let id = '#upload_' + this.filedFileName + '_' + name
                    let layIdx = alay.loading()
                    $.ajaxFileUpload({
                        url: "/File/UploadImage",
                        secureuri: false,
                        fileElementId: e.target.id,
                        dataType: 'text',
                        data: { type: "image" },
                        success: (res, status) => {
                            alay.close(layIdx)
                            e.target.value = ''
                            this.filedFileName = 'file_' + ((Math.random() * 10000000).toFixed(0) - 0)
                            res = JSON.parse(res);
                            if (res.state) {
                                let val = this.struc[idx].value ?? ''
                                if (val != '') val += ',' + res.data
                                else val = res.data
                                this.struc[idx].value = val
                            }
                            else
                                alay.msg(res.msg);
                        },
                        error: function (data, status, e) {
                            alay.msg(e);
                        }
                    });
                },
                delFile(idx1, idx2) {
                    let val = this.struc[idx1].value
                    let arr = val.split(',')
                    arr.splice(idx2, 1)
                    val = ''
                    for (item of arr) {
                        val += item + ','
                    }
                    val = val.substr(0, val.length - 1)
                    this.struc[idx1].value = val
                },
                showDataForm(val, idx) {
                    this.showData = true
                    this.editIndex = (this.pageIndex - 1) * this.pageSize + idx
                    this.fileIdName = 'file_' + ((Math.random() * 10000000).toFixed(0) - 0)
                    let pri = this.getPrimary()
                    let mod = [], temp = this.dataList.find(x => {
                        return x[pri] == val
                    })
                    for (item of this.struc) {
                        let mt = {}
                        for (filed in item) {
                            mt[filed] = item[filed]
                            if (filed == 'value') {
                                mt[filed] = temp[item.name]
                            }
                        }
                        mod.push(mt)
                    }
                    this.editData = mod
                },
                saveData() {
                    let idx = alay.loading()
                    $.post('/App/AxEditData', { tableid: this.selectedTable.id, index: this.editIndex, list: this.editData }, res => {
                        alay.close(idx)
                        if (res.state) {
                            this.axGetData()
                            this.showData = false
                        }
                        alay.msg(res.msg)
                    })
                },
                getPrimary() {
                    return this.struc.find(x => {
                        return x.defaultvalue == 'primary'
                    }).name
                },
                selectFileData(name) {
                    let id = '#upload_' + this.fileIdName + '_' + name
                    $(id).click()
                },
                uploadFileData(e, name) {
                    let idx = e.target.dataset.idx
                    let id = '#upload_' + this.fileIdName + '_' + name
                    let layIdx = alay.loading()
                    $.ajaxFileUpload({
                        url: "/File/UploadImage",
                        secureuri: false,
                        fileElementId: e.target.id,
                        dataType: 'text',
                        data: { type: "image" },
                        success: (res, status) => {
                            alay.close(layIdx)
                            e.target.value = ''
                            this.fileIdName = 'file_' + ((Math.random() * 10000000).toFixed(0) - 0)
                            res = JSON.parse(res);
                            if (res.state) {
                                let val = this.editData[idx].value ?? ''
                                if (val != '') val += ',' + res.data
                                else val = res.data
                                this.editData[idx].value = val
                            }
                            else
                                alay.msg(res.msg);
                            this.$forceUpdate()
                        },
                        error: function (data, status, e) {
                            alay.msg(e);
                        }
                    });
                },
                delFileData(idx1, idx2) {
                    let val = this.editData[idx1].value
                    let arr = val.split(',')
                    arr.splice(idx2, 1)
                    val = ''
                    for (item of arr) {
                        val += item + ','
                    }
                    val = val.substr(0, val.length - 1)
                    this.editData[idx1].value = val
                },
                showImages(val) {
                    if (!val) return ''
                    let arr = val.split(',')
                    let html = ''
                    for (item of arr) {
                        html += `<img src='${item}' alt='' />`
                    }
                    return html
                },
                deleteData(index) {
                    alay.confirm('确定删除数据吗？<br><span style="color:red;">删除后将无法找回！<span>', res => {
                        if (res) {
                            index = (this.pageIndex - 1) * this.pageSize + index
                            let idx = alay.loading()
                            $.post('/App/AxDelData', { tableid: this.selectedTable.id, index: index }, res => {
                                alay.close(idx)
                                if (res.state) {
                                    this.axGetData()
                                }
                                alay.msg(res.msg)
                            })
                        }
                    })
                },
                showDetail(val) {
                    this.isShowDetail = true
                    let pri = this.getPrimary()
                    let mod = [], temp = this.dataList.find(x => {
                        return x[pri] == val
                    })
                    for (item of this.struc) {
                        let mt = {}
                        for (filed in item) {
                            mt[filed] = item[filed]
                            if (filed == 'value') {
                                mt[filed] = temp[item.name]
                            }
                        }
                        mod.push(mt)
                    }
                    this.showDetailData = mod
                }
            }
        })
        vm.axGetApps()
    </script>
}
<div id="app">
    <div class="nav">
        <div>ApiData</div>
        <ul class="menu">
            <li>
                @ViewBag.Name
                <ul>
                    <li>修改密码</li>
                    <li>个人信息</li>
                    <li>关于</li>
                    <li>退出</li>
                </ul>
            </li>
        </ul>
    </div>
    <div class="panel">
        <div class="app">
            <h2>
                应用
                <a href="#" class="fa fa-plus-square-o" title="新建应用" @@click="showAppForm(0)"></a>
            </h2>
            <div class="app-list">
                <div class="ops" v-for="elm of apps" v-key="elm.id" :title="elm.note" :class="{'active' : selectedApp.id == elm.id}" @@click="selectApp(elm.id)">
                    <div>
                        {{elm.name}}
                    </div>
                    <div>AppID：{{elm.appid}}</div>
                    <div>
                        <a href="#" class="fa fa-edit" title="编辑应用" @@click.stop="showAppForm(elm.id)"></a>
                        <a href="#" class="fa fa-trash-o" title="删除应用" @@click.stop="delApp(elm.id)"></a>
                    </div>
                </div>
            </div>
        </div>
        <div class="table">
            <h2>
                数据表
                <a href="#" class="fa fa-plus-square-o" title="新建数据表" @@click="showTableForm(0)"></a>
            </h2>
            <div class="app-list">
                <div class="ops" v-for="elm of tables" v-key="elm.id" :title="elm.note" :class="{'active' : selectedTable.id == elm.id}" @@click="selectTable(elm.id)">
                    <div>
                        {{elm.name}}
                    </div>
                    <div>Code：{{elm.code}}</div>
                    <div>
                        <a href="#" class="fa fa-edit" title="编辑表" @@click.stop="showTableForm(elm.id)"></a>
                        <a href="#" class="fa fa-trash-o" title="删除表" @@click.stop="delTable(elm.id)"></a>
                    </div>
                </div>
            </div>
        </div>
        <div class="excute">
            <div class="tabs">
                <div :class="{active: tabIndex == 'data'}" @@click="selectTab('data')">数据</div>
                <div :class="{active: tabIndex == 'struc'}" @@click="selectTab('struc')">结构</div>
                <div :class="{active: tabIndex == 'insert'}" @@click="selectTab('insert')">增加数据</div>
                <div :class="{active: tabIndex == 'api'}" @@click="selectTab('api')">接口预览</div>
            </div>
            <div class="content">
                <div class="dataContainer" v-show="tabIndex == 'data'">
                    <table class="dataTable">
                        <thead>
                            <tr>
                                <th v-for="elm of struc" v-if="!elm.isnew">{{elm.des}}（{{elm.name}}）</th>
                                <th class="caozuo">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(elm,index) of dataList">
                                <template v-for="filed of struc">
                                    <td v-if="!filed.isnew && filed.type == 'string'">{{shortContent(elm[filed.name],128)}}</td>
                                    <td v-else v-html="showImages(elm[filed.name])"></td>
                                </template>
                                <td class="caozuo">
                                    <a href="#" title="编辑" class="fa fa-edit" @@click="showDataForm(elm[getPrimary()],index)"></a>
                                    <a href="#" title="详细" class="fa fa-info-circle" @@click="showDetail(elm[getPrimary()])"></a>
                                    <a href="#" title="删除" class="fa fa-trash-o" @@click="deleteData(index)"></a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div id="mypage"></div>
                </div>
                <div v-show="tabIndex == 'struc'">
                    <div class="struc-panel">
                        <div class="struc-btns">
                            <a class="btn btn-primary btn-anti btn-loading" @@click="addFiled">添加字段</a>
                            <a class="btn btn-success btn-anti" @@click="saveStruc">保存表结构</a>
                        </div>
                        <div class="struc-fileds">
                            <div>字段名</div>
                            <div>数据类型</div>
                            <div>设定</div>
                            <div>说明</div>
                            <div>操作</div>
                        </div>
                        <div class="struc-list">
                            <div class="ops" v-for="(elm,index) of struc">
                                <input type="text" class="f-name" v-model="elm.name" placeholder="字段名" />
                                <select v-model="elm.type" class="f-type">
                                    @foreach (var item in ApiData.Common.EnumHelper.GetSelectItems(typeof(ApiData.Common.EnumHelper.FiledDataType)))
                                    {
                                        <option value="@item.Key">@item.Key</option>
                                    }
                                </select>
                                <select v-model="elm.defaultvalue" class="f-default">
                                    <option value="primary">主键</option>
                                    <option value="">无</option>
                                </select>
                                <input type="text" v-model="elm.des" class="f-des" placeholder="字段说明" />
                                <input type="button" class="btn btn-danger btn-anti btn-xs" value="删除" @@click="removeFiled(index)" />
                            </div>
                        </div>
                    </div>
                </div>
                <div v-show="tabIndex == 'insert'">
                    <div class="add-panel" v-if="struc.length > 0">
                        <form class="form-panel">
                            <div class="form" @@keyup.enter="addData">
                                <div v-for="(elm,index) of struc" class="form-option">
                                    <template v-if="elm.type=='string'">
                                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                                        <input type="text" v-model="elm.value">
                                    </template>
                                    <template v-else>
                                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                                        <template v-if="elm.value">
                                            <label v-for="(e2,i2) of elm.value.split(',')"><input type="button" class="btn btn-xs btn-danger" value="×" @@click="delFile(index,i2)" /> <label>{{e2}}</label></label>
                                        </template>
                                        <input type="button" class="btn btn-xs btn-success btn-anti upload" value="上传" @@click="selectFile(elm.name)" />
                                        <input type="file" style="display:none;" :id="'upload_' + filedFileName + '_' +  elm.name" :name="'upload_' + filedFileName + '_' +  elm.name" :data-idx="index" @@change="uploadFile(event,elm.name)" />
                                    </template>
                                </div>
                                <div class="form-line">
                                    <input type="reset" class="btn" value="重置" />
                                    <a class="btn btn-primary" @@click="addData">保存</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div v-show="tabIndex == 'api'">
                    <div class="api-panel">
                        <div><a href="/Home/Doc" class="btn btn-primary btn-anti btn-loading" target="_blank">点此查看API接口文档</a></div>
                        <h2>查询表结构</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/struc</p>
                        <h2>查询所有数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/select</p>
                        <h2>获取随机数量的数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/random/[value]</p>
                        <h2>筛选主键查询一条数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/select/[value]</p>
                        <h2>自定义字段查询全部数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/select/[filed]/[value]</p>
                        <h2>自定义字段模糊查询全部数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/like/[filed]/[value]</p>
                        <h2>查询表的总数据量</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/page</p>
                        <h2>按分页查询当前页所有数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/page/[pageIndex]/[pageSize=10]</p>
                        <h2>查询字段的去重数据</h2>
                        <p>@(ViewBag.Domain)/data/{{usercode}}/{{selectedApp.appid ?? '[appid]'}}/{{selectedTable.code ?? '[table]'}}/distinct/[filed]</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="form-container" v-if="showApp">
        <div class="form-panel">
            <div class="form-title">编辑应用</div>
            <div class="form" @@keyup.enter="saveApp">
                <input type="hidden" v-model="editApp.id" />
                <div class=" form-option">
                    <label for="">AppID</label>
                    <input type="text" v-model="editApp.appid">
                </div>
                <div class=" form-option">
                    <label for="">名称</label>
                    <input type="text" v-model="editApp.name">
                </div>
                <div class=" form-option">
                    <label for="">备注</label>
                    <input type="text" v-model="editApp.note">
                </div>
                <div class=" form-line">
                    <a class="btn" @@click="showApp = false">取消</a>
                    <a class="btn btn-primary" @@click="saveApp">保存</a>
                </div>
            </div>
        </div>
    </div>
    <div class="form-container" v-if="showTable">
        <div class="form-panel">
            <div class="form-title">编辑数据表</div>
            <div class="form" @@keyup.enter="saveTable">
                <input type="hidden" v-model="editTable.id" />
                <div class=" form-option">
                    <label for="">TableCode</label>
                    <input type="text" v-model="editTable.code">
                </div>
                <div class=" form-option">
                    <label for="">名称</label>
                    <input type="text" v-model="editTable.name">
                </div>
                <div class=" form-option">
                    <label for="">备注</label>
                    <input type="text" v-model="editTable.note">
                </div>
                <div class=" form-line">
                    <a class="btn" @@click="showTable = false">取消</a>
                    <a class="btn btn-primary" @@click="saveTable">保存</a>
                </div>
            </div>
        </div>
    </div>
    <div class="form-container" v-if="showData">
        <form class="form-panel" style="width: 600px;">
            <div class="form-title">编辑数据</div>
            <div class="form" @@keyup.enter="saveData">
                <div v-for="(elm,index) of editData" class="form-option">
                    <template v-if="elm.type=='string'">
                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                        <input type="text" v-model="elm.value">
                    </template>
                    <template v-else>
                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                        <template v-if="elm.value">
                            <label v-for="(e2,i2) of elm.value.split(',')"><input type="button" class="btn btn-xs btn-danger" value="×" @@click="delFileData(index,i2)" /> <label>{{e2}}</label></label>
                        </template>
                        <input type="button" class="btn btn-xs btn-success btn-anti upload" value="上传" @@click="selectFileData(elm.name)" />
                        <input type="file" style="display:none;" :key="fileIdName" :id="'upload_' + fileIdName + '_' + elm.name" :name="'upload_' + fileIdName + '_' + elm.name" :data-idx="index" @@change="uploadFileData(event,elm.name)" />
                    </template>
                </div>
                <div class="form-line">
                    <a class="btn" @@click="showData = false">取消</a>
                    <input type="reset" class="btn" value="重置" />
                    <a class="btn btn-primary" @@click="saveData">保存</a>
                </div>
            </div>
        </form>
    </div>
    <div class="form-container" v-if="isShowDetail">
        <div class="form-panel" style="width: 80vw; height:80vh;">
            <div class="form-title">数据详情</div>
            <div class="form">
                <div v-for="(elm,index) of showDetailData" class="form-option">
                    <template v-if="elm.type=='string'">
                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                        <textarea readonly>{{elm.value}}</textarea>
                    </template>
                    <template v-else>
                        <label for="">{{elm.des}}（{{elm.name}}）</label>
                        <template v-if="elm.value">
                            <label v-for="(e2,i2) of elm.value.split(',')"><label>{{e2}}</label></label>
                        </template>
                    </template>
                </div>
                <div class="form-line">
                    <a class="btn btn-primary" @@click="isShowDetail = false">关闭</a>
                </div>
            </div>
        </div>
    </div>
</div>

